export default {
  //开启命名空间
  namespaced: true,
  
  //数据
  state: () => ({
    //用户信息对象
    userinfo: JSON.parse(uni.getStorageSync('userinfo') || '{}'),
    //登录状态
    hasLogin: uni.getStorageSync('hasLogin') || false
  }),
  
  //方法
  mutations: {
    updateUserInfo(state, userinfo) {
      state.userinfo = userinfo
      this.commit('m_user/saveUserInfoToStorage')
    },
    //持久化存储
    saveUserInfoToStorage(state) {
      uni.setStorageSync('userinfo', JSON.stringify(state.userinfo))
    },
    //更新登录状态
    updateLoginStatus(state, status) {
      state.hasLogin = status
      this.commit('m_user/saveLoginStatus')
    },
    saveLoginStatus(state) {
      uni.setStorageSync('hasLogin', state.hasLogin)
    },
    
    //清除用户信息（退出登录）
    clearUserInfo(state) {
      state.userinfo = {}
      state.hasLogin = false
      uni.removeStorageSync('userinfo')
      uni.removeStorageSync('hasLogin')
    }
  },
  
  // Actions
  actions: {
    //初始化登录状态
    initLoginStatus({ commit, state }) {
      const hasLogin = uni.getStorageSync('hasLogin')
      const userinfo = uni.getStorageSync('userinfo')
      if (hasLogin && userinfo) {
        commit('updateLoginStatus', true)
        // 确保 userinfo 是对象
        if (typeof userinfo === 'string') {
          commit('updateUserInfo', JSON.parse(userinfo))
        } else {
          commit('updateUserInfo', userinfo)
        }
      }
    }
  },
  
  getters: {
    //获取登录状态
    isLoggedIn: state => state.hasLogin && Object.keys(state.userinfo).length > 0
  }
}